package org.demo.mine.service;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.log4j.Log4j2;
import org.demo.mine.model.Box;
import org.demo.mine.model.BoxDashBoard;
import org.demo.mine.util.ListHashMap;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:LiaoYouLe
 * @Date: Created in 2018/8/31
 * @Description
 * @Modifyied By:
 */
@Service
@Log4j2
public class BoxService  {

    private Template blackTemplate;
    private Template mineTemplate;
    private Template safeTemplate;

    private BoxDashBoard boxDashBoard;

    public BoxService(Configuration configuration, BoxDashBoard boxDashBoard) throws IOException {

        blackTemplate = configuration.getTemplate("black_box.ftl");
        mineTemplate = configuration.getTemplate("mine_box.ftl");
        safeTemplate = configuration.getTemplate("safe_box.ftl");
        this.boxDashBoard = boxDashBoard;
    }






    public String getBoxArea(Integer id) throws IOException, TemplateException {
        ListHashMap<Integer, Box> boxArea = boxDashBoard.getBoxArea();
        log.info(Thread.currentThread().getId());

        Box clickBox = boxArea.getData(id);
        if (null != clickBox) {
            clickBox.unBoxing(boxArea);
        }

        StringBuffer area = new StringBuffer();
        Map context = new HashMap(2);
        String boxHtml;
        for (Box box : boxArea) {
            context.put("id", box.getId());
            context.put("num", box.getGroundMineNum());
            if (!box.hasUnBoxed()) {
                boxHtml = FreeMarkerTemplateUtils.processTemplateIntoString(blackTemplate, context);
            } else if (box.isMine()) {
                boxHtml = FreeMarkerTemplateUtils.processTemplateIntoString(mineTemplate, context);
            } else {
                boxHtml = FreeMarkerTemplateUtils.processTemplateIntoString(safeTemplate, context);
            }
            area.append(boxHtml);
        }
        return area.toString();
    }
}
